#include "GLBackGround.h"
#include "GLRenderComp.h"
#include "RenderController.h"
#include "common.h"
#include <QOpenGLShaderProgram>
void GLBackground::initData()
{
	if (mInited)
	{
		return;
	}
	mInited = true;
	// 生成VBO
	glGenBuffers(1, &mVertexVBO);
	glGenBuffers(1, &mTexCoordsVBO);
	// 生成VAO
	glGenVertexArrays(1, &mVAO);

	glBindVertexArray(mVAO);
	{
		const uint32_t vertexLocation	= 0;
		const uint32_t texCoordLocation = 1;

		// 顶点 Buffer的配置
		glBindBuffer(GL_ARRAY_BUFFER, mVertexVBO);
		{
			glEnableVertexAttribArray(vertexLocation);
			glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(QVector3D), (void*)0);
		}
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		glBindBuffer(GL_ARRAY_BUFFER, mTexCoordsVBO);
		{
			glEnableVertexAttribArray(texCoordLocation);
			glVertexAttribPointer(texCoordLocation, 2, GL_FLOAT, GL_FALSE, sizeof(QVector2D), (void*)0);
		}
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}
	glBindVertexArray(0);

	updateData();
}
void GLBackground::initTexture()
{
	qDebug() << "GLBackground::initTexture()";
	mImage	 = QImage(":/img/background.jpg");
	mTexture = genTexture(mImage);
}

void GLBackground::updateData()
{
	mTextureCoords.clear();
	mTextureCoords << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) << QVector2D(0, 1);
	QRect backgroundRect;
	int	  pw = mImage.width();
	int	  ph = mImage.height();

	pw		  = (int)(1.0 * pw * mScale);
	ph		  = (int)(1.0 * ph * mScale);
	auto size = gController->viewSize();
	backgroundRect.setX((size.width() - pw) / 2);
	backgroundRect.setY((size.height() - ph) / 2);
	backgroundRect.setWidth(pw);
	backgroundRect.setHeight(ph);

	mVertices = rectToVertices(backgroundRect, size.width(), size.height());

	glBindBuffer(GL_ARRAY_BUFFER, mVertexVBO);
	{
		glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D) * mVertices.size(), mVertices.constData(), GL_STATIC_DRAW);
	}
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	// 矩阵数据从内存传到GPU显存
	glBindBuffer(GL_ARRAY_BUFFER, mTexCoordsVBO);
	{
		glBufferData(GL_ARRAY_BUFFER, sizeof(QVector2D) * mTextureCoords.size(), mTextureCoords.constData(), GL_STATIC_DRAW);
	}
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void GLBackground::paint(QOpenGLShaderProgram* program, const QMatrix4x4& mvpMat)
{
	if (!program->bind())
	{
		return;
	}
	glBindVertexArray(mVAO);
	{
		mTexture->bind();
		program->setUniformValue("qt_ModelViewProjectionMatrix", mvpMat);
		program->setUniformValue("qt_Texture0", 0);
		glDrawArrays(GL_TRIANGLE_FAN, 0, mVertices.size());
	}
	glBindVertexArray(0);
}
